pp108 : Best Practices for Developers in Using Logging Framework

Best Practices for Developers in Using Logging Framework

This topic describes the best practices for developers while using Logging Framework.
The following guidelines can help a developer to use the logging framework better:
  • Once the logging instance is obtained, it should be made as a static object. The same instance must be used subsequently.
    public class LoggerDemo1 {
    	private static final CordysLogger logger = CordysLogger.getCordysLogger(LoggerDemo1.class);
    	
    	public void methodOne() 
    	{
    	}
    
    }
  • Before using the logger, check whether the selected category is enabled with specified severity. This can save a performance penalty for composing the arguments. Don't do this for error or fatal.
    Note: The error and fatal severities are configured for logging by default, so there is no value in adding calls to isErrorEnabled () and isFatalEnabled (); it only clutters the code.
  • It is a best practice to make the log messages translatable (the nontranslatable APIs are deprecated).
    public class LoggerDemo2 {
    	static CordysLogger logger = CordysLogger.getCordysLogger(LoggerDemo2.class);
    	
    	public void methodZero() 
    	{
    		int node = 0; // get a NOM node
    		if (logger.isDebugEnabled()) 
    		{
    			logger.debug(node);
    			logger.debug("Hi there"); // don't use translateable messages for debugging, those are meant for (peer) developers.
    		}
    	}
    	
    	public void methodOne() 
    	{
    		if (logger.isInfoEnabled()) 
    		{
    			logger.info(Messages.INFORM_ADMINSTRATOR);
    		}
    	}
    	
    	public void methodThree() 
    	{
    		try
    		{
    			// do something...
    		}
    		catch(Exception e)
    		{
    			logger.error(e, Messages.ERROR_WHILE_THREE);
    		}
    	}
    	
    	public void methodFour() 
    	{
    		if (logger.isInfoEnabled())
    		{
    			logger.info(Messages.INFORM_STATUS, status); // use insertions
    		}
    	}
    }
    
  • If the logger is used to log any exception based messages, it must pass the whole exception to the logger; not just the message:
    public class LoggerDemo3 {
    	static CordysLogger logger = CordysLogger.getCordysLogger(LoggerDemo3.class);
    	
    	public void methodOne() 
    	{
    		try
    		{
    			// do something...
    		}
    		catch(Exception e)
    		{
    			logger.error(e, Messages.ERROR_WHILE_THREE);
    			// Don't do this: logger.error(null, Messages.ERROR_WHILE_THREE, e.getMessage());
    		}
    	}
    }